<template>
  <div class="panel">
    <el-form
      ref="formRef"
      :rules="operateRules"
      :model="operatePost"
      class="demo-form-inline"
      label-width="140px">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="activityName" label="活动名称">
            <el-input
              maxlength="20"
              v-model="operatePost.activityName"
              style="max-width: 420px"
              placeholder="20个字以内"
            ></el-input>
          </el-form-item>
          <el-form-item prop="activityTime" label="活动时间">
            <el-date-picker
              style="width: 420px"
              v-model="postSignUpDate"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled="isEdit"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :disabled-date="limitstartTimeDate"
              @change="signUpDateChange"
            />
          </el-form-item>
          <el-form-item prop="coverImage" :label="'列表封面图\n(220px*292px，大小不超过30kb)'">
            <upload-oss
              list-type="picture-card"
              :limit="1"
              :imageUrl="imageUrlList.coverImage"
              :beforeUpload="(e) => beforeUpload(e, 30)"
              @upload="(e) => afterUpload(e, 'coverImage')"
            ></upload-oss>
          </el-form-item>
          <el-form-item prop="bannerImageList" :label="'详情banner图\n(750px*1000px，大小不超过200kb)'">
            <upload-oss
              list-type="picture-card"
              :limit="5"
              :imageUrl="imageUrlList.bannerImageList"
              :beforeUpload="(e) => beforeUpload(e, 200)"
              @upload="(e) => afterUpload(e, 'bannerImageList')"
            ></upload-oss>
          </el-form-item>
          <el-form-item prop="assistCardImage" :label="'助力卡片图\n(480px*384px，大小不超过40kb)'">
            <upload-oss
              list-type="picture-card"
              :limit="1"
              :imageUrl="imageUrlList.assistCardImage"
              :beforeUpload="(e) => beforeUpload(e, 40)"
              @upload="(e) => afterUpload(e, 'assistCardImage')"
            ></upload-oss>
          </el-form-item>
          <el-form-item prop="assistPosterImage" :label="'助力海报图\n(750px*1250px，大小不超过200kb)'">
            <upload-oss
              list-type="picture-card"
              :limit="1"
              :imageUrl="imageUrlList.assistPosterImage"
              :beforeUpload="(e) => beforeUpload(e, 200)"
              @upload="(e) => afterUpload(e, 'assistPosterImage')"
            ></upload-oss>
          </el-form-item>
          <el-form-item prop="description" label="活动规则">
            <tinymce
              v-model:value="operatePost.description"
              style="width: 750px"
              ref="myEditor"
            />
          </el-form-item>
          <el-form-item prop="activityPlay" label="玩法">
            <div style="margin-bottom: 10px">
              <el-checkbox label="每拉新1人获得" v-model="isCheckboxes.invite" :disabled="isEdit"/>
              <el-input-number
                v-model="operatePost.inviteConfig.assistanceValue"
                :min="1"
                :max="999999"
                controls-position="right"
                style="width: 100px;margin:0 10px"
                :disabled="isEdit"
              />
              <span class="label">总上限</span>
              <el-input-number
                v-model="operatePost.inviteConfig.upperLimit"
                :max="999999"
                :min="1"
                controls-position="right"
                style="width: 100px;margin:0 10px"
                :disabled="isEdit"
              />
            </div>
            <div>
              <el-checkbox label="每唤醒1人获得" name="1" v-model="isCheckboxes.wake" :disabled="isEdit"/>
              <el-input-number
                v-model="operatePost.wakeConfig.assistanceValue"
                :min="1"
                :max="999999"
                controls-position="right"
                style="width: 100px;margin:0 10px"
                :disabled="isEdit"
              />
              <span class="label">总上限</span>
              <el-input-number
                v-model="operatePost.wakeConfig.upperLimit"
                :max="999999"
                :min="1"
                controls-position="right"
                style="width: 100px;margin:0 10px"
                :disabled="isEdit"
              />
            </div>
          </el-form-item>
          <el-form-item label="中奖设置" prop="activityPrize">
            <el-radio-group v-model="operatePost.winnerConfigType" @change="changeWinnerConfigType" :disabled="isEdit">
              <el-radio :label="0">按名次获奖</el-radio>
              <el-radio :label="1">按助力门槛获奖</el-radio>
            </el-radio-group>
            <template v-if="operatePost.winnerConfigType  === 0">
              <div v-for="(winner, index) in operatePost.winnerConfig" :key="index" style="margin-bottom:10px">
                <span class="label">助力值第{{winner.from}}名至</span>
                <el-input-number
                  v-model="winner.to"
                  :max="999999"
                  :min="winner.from"
                  controls-position="right"
                  style="width: 100px;margin:0 10px"
                  @change="changeWinnerRank"
                  :disabled="isEdit"
                />
                <span class="label">名获得</span>
                <el-input v-model="winner.prize" placeholder="几等奖/奖品" style="width:120px;margin:0 10px" :disabled="isEdit" maxlength="6" />
                <el-button type="primary" size="small" v-if="index === 0" :icon="Plus" @click="addActivityPrize()" :disabled="isEdit" />
                <el-button type="danger" size="small" v-else :icon="SemiSelect" @click="deteleActivityPrize(index)" :disabled="isEdit" />
              </div>
            </template>
            <template v-if="operatePost.winnerConfigType === 1">
              <div v-for="(door, index) in operatePost.winnerConfig" :key="index" style="margin-bottom:10px">
                <span class="label">助力值≥</span>
                <el-input-number
                  v-model="door.from"
                  :max="operatePost.winnerConfig[index - 1] ? operatePost.winnerConfig[index - 1].from - 1 : 999999"
                  :min="0"
                  controls-position="right"
                  style="width: 100px;margin:0 10px"
                  :disabled="isEdit"
                />
                <span class="label">的前</span>
                <el-input-number
                  v-model="door.to"
                  :max="999999"
                  :min="1"
                  controls-position="right"
                  style="width: 100px;margin:0 10px"
                  :disabled="isEdit"
                />
                <span class="label">名获得</span>
                <el-input v-model="door.prize" placeholder="几等奖/奖品" style="width:120px;margin:0 10px" :disabled="isEdit" maxlength="6" />
                <el-button type="primary" size="small" v-if="index === 0" :icon="Plus" @click="addActivityPrize()" :disabled="isEdit" />
                <el-button type="danger" size="small" v-else :icon="SemiSelect" @click="deteleActivityPrize(index)" :disabled="isEdit" />
              </div>
            </template>
          </el-form-item>
          <el-form-item label="上架消息推送" required>
            <el-switch v-model="operatePost.isPushConfig" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="设置上架状态" required>
            <el-radio-group v-model="operatePost.activityStatus">
              <el-radio :label="0">下架</el-radio>
              <el-radio :label="1">上架</el-radio>
            </el-radio-group>
            <template v-if="operatePost.activityStatus === 1">
              <el-date-picker v-model="operatePost.listingTime" type="datetime" placeholder="选择上架时间" :disabled-date="limitStackiDate" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div style="margin: 0 auto">
          <el-button
            class="submitBtn"
            type="primary"
            plain
            v-if="operatePost.activityStatus === -1 || !isEdit"
            @click="submitPre(formRef, 2)">存为草稿</el-button>
          <el-button
            class="submitBtn"
            type="primary"
            plain
            @click="submitPre(formRef, 1)">预览</el-button>
          <el-button
            class="submitBtn"
            type="primary"
            plain
            @click="submitPre(formRef, 0)"
            >提交</el-button> 
        </div>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, watchEffect, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useStore } from '@/store'
import UploadOss from '@/components/AliOSS'
import { Plus, SemiSelect } from '@element-plus/icons-vue'
import { getAppletsCode } from '@/api/tool'
import { addMarketEvents, getMarketEventsDetail } from '@/api/eventsinfo.js'
import Tinymce from "@/components/Tinymce"
// 管理所有添加字段
const _POST = {
  activityName: '',
  startTime: '',
  endTime: '',
  bannerImageList: [],
  coverImage: '',
  assistCardImage: '',
  assistPosterImage: '',
  description: '',
  thresholdType: false,
  assistThresholdType: false,
  inviteConfig: {
    assistanceValue: 1,
    upperLimit: 1
  },
  wakeConfig: {
    assistanceValue: 1,
    upperLimit: 1
  },
  winnerConfig: [
    {
      from: 1,
      to: 1,
      prize:''
    }
  ],
  isPushConfig: 0,
  activityStatus: 0,
  listingTime: '',
  winnerConfigType: 0
}
const imageUrlList = ref({
  coverImage: [],
  bannerImageList: [],
  assistCardImage: [],
  assistPosterImage: []
})
const isCheckboxes = ref({
  invite: false,
  wake: false
})
const myEditor = ref(null)
const postSignUpDate = ref([])
const store = useStore();
const router = useRouter();
const isEdit = ref(false)
const params = ref({});
const operatePost = ref({
  ..._POST
})
const getImageDimensions = async(imageUrl, width, height) => {
  const image = new Image()
  image.src = imageUrl
  return new Promise((resolve, reject) => {
    image.onload = () => {
      if (image.width !== width) {
        resolve(false)
      }
      if (image.height !== height) {
        resolve(false)
      }
      resolve(true)
    }
    image.onerror = reject
  })
}
const checkActivityTime = (rule, value, callback) => {
  if (!operatePost.value.startTime || !operatePost.value.endTime) {
    return callback('请选择活动报名时间')
  }
  callback()
}
const checkActivityImage = (rule, value, callback) => {
  if (!operatePost.value[rule.fullField].length) {
    switch (rule.fullField) {
      case 'coverImage':
        return callback('请上传列表封面')
      case 'assistCardImage':
        return callback('请上传助力卡片图')
      case 'bannerImageList':
        return callback('请上传列表封面')
      case 'assistPosterImage':
        return callback('请上传助力海报图')
      default:
        break;
    }
  }
  callback()
}
const checkActivityPlay = (rule, value, callback) => {
  if (!isCheckboxes.value.invite && !isCheckboxes.value.wake) {
    return callback('请选择活动玩法')
  }
  if (isCheckboxes.value.invite && (operatePost.value.inviteConfig.upperLimit % operatePost.value.inviteConfig.assistanceValue) !== 0) {
    return callback('助力值上限必须是助力值的整数倍')
  }
  if (isCheckboxes.value.wake && (operatePost.value.wakeConfig.upperLimit % operatePost.value.wakeConfig.assistanceValue) !== 0) {
    return callback('唤醒值上限必须是唤醒值的整数倍')
  }
  callback()
}
const checkActivityPrize = (rule, value, callback) => {
  if (operatePost.value.winnerConfigType === 0) {
    operatePost.value.winnerConfig.forEach(item => {
    if (!item.prize) {
        return callback('中奖设置填写不正确')
      }
    })
  } else {
    console.log(999)
  }
  callback()
}
const operateRules = ref({
  activityName: [{required: true, message: '请输入活动名称', trigger: 'blur'}],
  activityTime: [{required: true, validator: checkActivityTime, trigger: 'change' }],
  coverImage: [{required: true, validator: checkActivityImage, trigger: 'blur'}],
  assistCardImage: [{required: true, validator: checkActivityImage, trigger: 'blur'}],
  bannerImageList: [{required: true, validator: checkActivityImage, trigger: 'blur'}],
  assistPosterImage: [{required: true, validator: checkActivityImage, trigger: 'blur'}],
  description: [{required: true, message: '请输入活动说明', trigger: 'blur'}],
  activityPlay: [{required: true, validator: checkActivityPlay, trigger: 'change'}],
  activityPrize: [{required: true, validator: checkActivityPrize, trigger: 'blur'}]
})
const limitStackiDate = (time) => {
  // 如果没有后面的 -8.64e7 就是不可以选择今天的
  const beginDate = new Date().getTime() - 8.64e7;
  const endDate = new Date("2300-01-01 00:00:00").getTime()
  return beginDate > time.getTime() || endDate < time.getTime()
}
const formRef = ref({})
const _getBannerIamge = (urlArry) => {
  const arr = []
  urlArry.forEach(item => {
    arr.push({ url: item })
  })
  return arr
}
const getActivtyDetail = (id) => {
  getMarketEventsDetail(id).then(res => {
    if(res.code === 0) {
      operatePost.value = {
        activityName: res.data.activityName,
        startTime: res.data.startTime,
        endTime: res.data.endTime,
        bannerImageList: res.data.bannerImageList,
        coverImage: res.data.coverImage,
        assistCardImage: res.data.assistCardImage,
        assistPosterImage: res.data.assistPosterImage,
        description: res.data.description,
        thresholdType: !!res.data.thresholdType,
        assistThresholdType: !!res.data.assistThresholdType,
        inviteConfig: res.data.inviteConfig,
        wakeConfig: res.data.wakeConfig,
        winnerConfig: res.data.winnerConfig,
        isPushConfig: res.data.isPushConfig,
        activityStatus: res.data.activityStatus,
        id: res.data.id,
        listingTime: res.data.listingTime,
        winnerConfigType: res.data.winnerConfigType
      }
      postSignUpDate.value = [res.data.startTime, res.data.endTime]
      imageUrlList.value = {
        coverImage: [{ url: res.data.coverImage }],
        assistCardImage: [{ url: res.data.assistCardImage }],
        assistPosterImage: [{ url: res.data.assistPosterImage }],
        bannerImageList: _getBannerIamge(res.data.bannerImageList)
      }
      isCheckboxes.value = {
        invite: JSON.stringify(res.data.inviteConfig) !== '{}',
        wake: JSON.stringify(res.data.wakeConfig) !== '{}'
      }
      myEditor.value.setContent(res.data.description)
      isEdit.value = res.data.activityStatus !== -1
      // console.log(66666, myEditor.value)
    }
  })
}
const getCode = (id) => {
  getAppletsCode({
    scene: 'mp4',
    page: 'events/eventsMarket',
    param: 'preview=true&id=' + id
  }).then(res => {
    if(res.code === 0){
      const blobData = "data:image/png;base64,"+ res.data
      ElMessageBox.alert(
        `<img src=${blobData} style='width: 360px'>`,
        '',
        {
          dangerouslyUseHTMLString: true,
        }
      )
    }
  })
}
const submitPre = (formRef, operationType) => {
  if (!formRef) return
  formRef.validate(async(valid) => {
    if (valid) {
      const data = JSON.parse(JSON.stringify(operatePost.value))
      // 列表封面图
      const _coverImage = await getImageDimensions(operatePost.value.coverImage, 220, 292)
      if (!_coverImage) {
        ElMessage.warning('列表封面图尺寸不对');
        return
      }
      // 详情banner图
      const _bannerImageList = await getImageDimensions(operatePost.value.bannerImageList[0], 750, 1000)
      if (!_bannerImageList) {
        ElMessage.warning('详情banner图尺寸不对')
        return
      }
      const _assistCardImage = await getImageDimensions(operatePost.value.assistCardImage, 480, 384)
      if (!_assistCardImage) {
        ElMessage.warning('助力卡片图尺寸不对');
        return
      }
      const _assistPosterImage = await getImageDimensions(operatePost.value.assistPosterImage, 750, 1250)
      if (!_assistPosterImage) {
        ElMessage.warning('助力海报图尺寸不对');
        return
      }
      if (operationType === 0 && operatePost.value.activityStatus === -1) {
        ElMessage.warning("请选择上下架状态")
        return
      }
      if (!isCheckboxes.value.invite) {
        delete data.inviteConfig
      }
      if (!isCheckboxes.value.wake) {
        delete data.wakeConfig
      }
      data.thresholdType = data.thresholdType ? 1: 0
      data.assistThresholdType = data.assistThresholdType ? 1: 0
      if (operationType === 2) {
        delete data.activityStatus
      }
      addMarketEvents({
        ...data,
        operationType
      }, operatePost.value.id ? 'PUT' : 'POST').then(res => {
        if (res.code === 0) {
          if (operationType === 1) {
            getCode(operatePost.value.id || res.data)
          } else {
            ElMessage.success('修改成功！')
            store.dispatch('tagsView/delView', { ...router.currentRoute.value }).then(() => {
              router.replace({ path: '/eventsInfo/marketList' })
            })
          }
        }
      })
    }
  })
}
const limitstartTimeDate = (time) => {
  // 如果没有后面的 -8.64e7 就是不可以选择今天的
  const beginDate = new Date().getTime() - 8.64e7;
  const endDate = new Date(operatePost.value.eventsStartTime || "2300-01-01 00:00:00").getTime();
  return beginDate > time.getTime() || endDate < time.getTime();
}
const signUpDateChange = (datetime) => {
  operatePost.value.startTime = !!datetime && datetime.length == 2 ? datetime[0] : ''
  operatePost.value.endTime = !!datetime && datetime.length == 2 ? datetime[1] : ''
}
const beforeUpload = (file, size) => {
  return new Promise((resolve, reject) => {
    const _size = (size + 1) * 1024
    if (file.size > _size) {
      ElMessage.error(`图片大小不能超过 ${size}kb！, 当前大小为${(file.size / 1024).toFixed(1)}kb`);
      reject();
      return;
    }
    resolve();
  });
}
const afterUpload = (list, type) => {
  const url = list[0]
  if (!url) {
    operatePost.value[type] = type === 'bannerImageList' ? [] : ''
  } else {
    if (type === 'bannerImageList') {
      const _arr = []
      list.forEach(item => {
        _arr.push(item.showUrl ? 'https://img.qumoyugo.com' + item.showUrl : item.url)
      })
      operatePost.value.bannerImageList = _arr
    } else {
      operatePost.value[type] = 'https://img.qumoyugo.com' + url.showUrl
    }
    console.log(operatePost.value.bannerImageList)
  }
}
const addActivityPrize = () => {
  if (operatePost.value.winnerConfigType === 0) {
    const len = operatePost.value.winnerConfig.length
    operatePost.value.winnerConfig.push({
      from: operatePost.value.winnerConfig[len - 1].to + 1,
      to: operatePost.value.winnerConfig[len - 1].to + 1,
      prize:''
    })
  }
  if (operatePost.value.winnerConfigType === 1) {
    const len = operatePost.value.winnerConfig.length
    operatePost.value.winnerConfig.push({
      from: 1,
      to: 1,
      prize:''
    })
  }
}
// 遍历重新赋值
const resetCountPrize = () => {
  operatePost.value.winnerConfig.forEach((item, index, arry) => {
    console.log(index, item.from, item.to)
    item.from = index === 0 ? 1 : arry[index - 1].to + 1
    if (item.to < item.from) {
      item.to = item.from
    }
  })
}
const deteleActivityPrize = (index) => {
  operatePost.value.winnerConfig.splice(index, 1)
  resetCountPrize()
}
const changeWinnerRank = () => {
  resetCountPrize()
}
const changeWinnerConfigType = () => {
  operatePost.value.winnerConfig = [{
    from: 1,
    to: 1,
    prize:''
  }]
} 
watchEffect(() => {
  params.value = router.currentRoute.value.params;
  // isEdit.value = !!params.value.id
  if (params.value.id) {
    getActivtyDetail(params.value.id)
  }
})
</script>

<style scoped lang="scss">
.panel {
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
}
.submitBtn {
  float: right;
  margin-right: 40px;
}
.label{
  font-size: var(--el-font-size-base);
  color: var(--el-text-color-regular);
}
</style>
